package com.shuai.utils.hander.securityHander;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用来解决认证过的用户访问无权限资源时的异常
 *
 * @author shuai
 * @since 2022
 */
@Slf4j
@Component
public class CustomAccessDeineHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {

        //设置返回状态码 401
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        //设置返回数据的字符集
        response.setContentType("application/json;charset=utf-8");
        //设置返回的数据
        response.getWriter().write(JSON.toJSONString(e.toString()));
    }
}